# !/usr/bin/env python3
# -*- coding: utf-8 -*-

import json
from urllib import request, parse
from app import mlog

__author__ = 'InG_byr'


def sdn_get_all_host():
    """
    get all hosts from onos
    :return:  hosts dict
    """
    m_error = None
    try:
        with request.urlopen('http://127.0.0.1:8181/onos/foo/blacklist/allHost') as f:
            raw_data = f.read().decode('utf-8')
            raw_hosts = json.loads(str(raw_data))
            hosts = raw_hosts['hosts']
    except Exception as e:
        hosts = None
        m_error = str(e)

    #         # test mode
    #         raw_data = """{
    #   "hosts": [
    #     {
    #       "id": "46:E4:3C:A4:17:C8/-1",
    #       "mac": "46:E4:3C:A4:17:C8",
    #       "vlan": "-1",
    #       "ipAddresses": [
    #         "127.0.0.1"
    #       ],
    #       "location": {
    #         "elementId": "of:0000000000000002",
    #         "port": "3"
    #       }
    #     },
    #         {
    #       "id": "56:E4:3C:A4:17:C8/-1",
    #       "mac": "56:E4:3C:A4:17:C8",
    #       "vlan": "-1",
    #       "ipAddresses": [
    #         "127.0.0.5"
    #       ],
    #       "location": {
    #         "elementId": "of:5000000000000002",
    #         "port": "5"
    #       }
    #     }
    #   ]
    # }"""
    #         raw_hosts = json.loads(str(raw_data))
    #         hosts = raw_hosts['hosts']
    #         m_error = None
    finally:
        return hosts, m_error


def sdn_manange_black_list(raw_data, op):
    """
    block some host
    :param raw_data: list, host information
    :return: blacked host
    """
    # todo: get virtual mac or ip
    local_mac = '46:E4:3C:A4:17:C8'

    hosts, get_error = sdn_get_all_host()
    target = []
    local_host, response_data, post_error = None, None, None
    # local_mac = lh.get_local_mac()

    data = raw_data[3:].split(' | ')
    for item in data:
        mlog.debug('target hosts: ' + item)
    if get_error:
        mlog.error(get_error)
        get_error = '[error] get the host list failed'
        return response_data, post_error, get_error
    for host in hosts:
        for item in data:
            if host['mac'] == item:
                target.append(host)
        if host['mac'] == local_mac:
            local_host = host
    if not local_host:
        get_error = '[error]get local mac address failed'
        return response_data, post_error, get_error, raw_data
    elif not target:
        get_error = '[error]targets do not exist'
        return response_data, post_error, get_error, raw_data
    else:
        raw_data = {'hosts': target,
                    'web_host': local_host}
        post_data = json.dumps(raw_data)
        mlog.debug('post data ' + post_data)

        try:
            if op == 0:
                mlog.debug('black host')
                url = 'http://127.0.0.1:8181/onos/foo/blacklist/sendBlacklist'
            elif op == 1:
                mlog.debug('remove host')
                url = 'http://127.0.0.1:8181/onos/foo/blacklist/rmFromBlacklist'
            else:
                mlog.ERROR('bad options')
                post_error = 'bad options'
                return response_data, post_error, get_error, raw_data
            req = request.Request(url)
            req.add_header('Accept', 'application/json')
            with request.urlopen(req, data=post_data.encode('utf-8')) as f:
                response_data = f.read.decode('utf-8')
                mlog.debug('Status:' + f.status + f.reason)
        except Exception:
            post_error = '[error]send data failed'
            response_data = None
        finally:
            return response_data, post_error, get_error, raw_data


def remote_black_hosts(response_data):
    black_list = json.loads(response_data)
    return black_list


def sdn_verify_route(src_host, dst_host):
    url = 'http://127.0.0.1:8181/onos/verify_route/hosts'
    post_data = json.dumps({'src_host': src_host, 'dst_host': dst_host})
    mlog.debug('post data ' + post_data)
    req = request.Request(url)
    req.add_header('Accept', 'application/json')
    response = None
    try:
        with request.urlopen(req, data=post_data.encode('utf-8')) as f:
            mlog.debug('status ', f.status, f.reason)
            mlog.debug('response ', f.read().decode('utf-8'))
            response = json.loads(f.read().decode('utf-8'))
    except Exception:
        response = {"route": "S1,S2,S4"}
        #return response
    finally:
        return response
